package akbderby;

import java.io.IOException;

import org.slim3.controller.Navigation;

import scenic3.annotation.ActionPath;
import scenic3.annotation.Default;
import scenic3.annotation.Page;
import scenic3.annotation.Var;
import akbderby.page.BasePage;
import akbderby.service.InfoService;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Page("/")
public class FrontPage extends BasePage {
    // /view/100 /view/200
    @ActionPath("view/{id}")
    public Navigation view(@Var("id") String id) {
        super.request.setAttribute("id", id);
        return forward("/view.jsp");
    }

    @ActionPath("mode/{pageMode}")
    public Navigation mode(@Var("pageMode") String pageMode) {
        sessionScope("pageMode", pageMode);
        return forward("/index.jsp");
    }

    @ActionPath("logon")
    public Navigation logon() {
        if (getUser().isAuthentication()) {
            return redirect(basePath);
        } else {
            try {
                UserService userService = UserServiceFactory.getUserService();
                response.sendRedirect(userService.createLoginURL(request
                    .getRequestURI()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @ActionPath("logout")
    public Navigation logout() {
        if (!getUser().isAuthentication()) {
            return redirect(basePath);
        } else {
            try {
                UserService userService = UserServiceFactory.getUserService();
                response.sendRedirect(userService.createLogoutURL(request
                    .getRequestURI()));
                getUser().setAuthentication(false);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    // /
    @Default
    public Navigation index() {
        InfoService service = new InfoService();
        requestScope("top5List", service.getTop5List());

        sessionScope("pageMode", requestScope("mode"));
        return forward("/index.jsp");
    }
}